package com.atguigu.process.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.model.process.Process;
import com.atguigu.model.process.ProcessRecord;
import com.atguigu.model.process.ProcessTemplate;
import com.atguigu.model.system.SysUser;
import com.atguigu.process.mapper.OaProcessMapper;
import com.atguigu.process.service.OaProcessRecordService;
import com.atguigu.process.service.OaProcessService;
import com.atguigu.process.service.OaProcessTemplateService;
import com.atguigu.security.custom.LoginUserInfoHelper;
import com.atguigu.vo.process.ApprovalVo;
import com.atguigu.vo.process.ProcessFormVo;
import com.atguigu.vo.process.ProcessQueryVo;
import com.atguigu.vo.process.ProcessVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class ProcessServiceImpl extends ServiceImpl<OaProcessMapper, Process> implements OaProcessService {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private OaProcessMapper processMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private OaProcessTemplateService processTemplateService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private OaProcessRecordService processRecordService;

    @Autowired
    private HistoryService historyService;


    @Override
    public IPage<ProcessVo> selectPage(Page<ProcessVo> pageParam, ProcessQueryVo processQueryVo) {
        IPage<ProcessVo> page = processMapper.selectPage(pageParam, processQueryVo);
        return page;
    }


    //部署流程定义
    @Override
    public void deployByZip(String deployPath) {
        //获取zip文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(deployPath);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        //部署
        Deployment deployment = repositoryService.createDeployment()
                .addZipInputStream(zipInputStream)
                .deploy();

        System.out.println(deployment.getId());
        System.out.println(deployment.getName());
    }

    //启动流程实例
    @Override
    public void startUp(ProcessFormVo processFormVo) {
        //1.根据当前用户id获取用户信息,TokenAuthenticationFilter.java里面已经放好了LoginUserInfoHelper
        SysUser sysUser = sysUserService.getById(LoginUserInfoHelper.getUserId());
        //2.根据模板id查询模板信息
        ProcessTemplate processTemplate = processTemplateService.getById(processFormVo.getProcessTemplateId());
        //3.保存提交的审批信息到oa_process表
        Process process=new Process();
        BeanUtils.copyProperties(processFormVo,process);//将processFormVo对象的值复制到process
        //其他值就set
        process.setStatus(1);
        String workNo = System.currentTimeMillis() + "";
        process.setProcessCode(workNo);
        process.setUserId(LoginUserInfoHelper.getUserId());
        process.setFormValues(processFormVo.getFormValues());
        process.setTitle(sysUser.getName() + "发起" + processTemplate.getName() + "申请");
        baseMapper.insert(process);
        //4.启动一个流程实例--RuntimeService
        //流程定义的key。业务key，就是processId。流程参数，form表单数据,转化为map集合
        String processDefinitionKey = processTemplate.getProcessDefinitionKey();
        //业务key，就是processId
        String businessKey = String.valueOf(process.getId());
        //流程参数，form表单数据,转化为map集合
        String formValues = processFormVo.getFormValues();
        JSONObject jsonObject = JSON.parseObject(formValues);
        //formData是前端传的参数:请假天数，开始时间，结束时间，理由-----》variales
        JSONObject formData = jsonObject.getJSONObject("formData");
        //遍历formData，封装到map集合
        HashMap<String, Object> map = new HashMap<>();
        for (Map.Entry<String,Object> entry:formData.entrySet()){
            map.put(entry.getKey(),entry.getValue());

        }
        HashMap<String, Object> variables = new HashMap<>();
        variables.put("data",map);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, variables);
        //5.查询下一个审批人是谁,activity会自动进行推进，我们查出来只是为了给下一个审批人推送消息，更新数据
        //审批人可能有多个
        List<Task> taskList=this.getCurrentTaskList(processInstance.getId());
        List<String> nameList=new ArrayList<>();  //放真实姓名
        for (Task task:taskList){
            //得到当前审批人
            String assigneeName = task.getAssignee();
            SysUser user = sysUserService.getUserByUsername(assigneeName);
            //得到真实的姓名
            String name = user.getName();
            nameList.add(name);
        }
        //TODO 6.发送消息给下一个审批人

        //将流程实例的id放到process
        process.setProcessInstanceId(processInstance.getId());
        process.setDescription("等待"+ StringUtils.join(nameList.toArray(), ",") +"审批");
        //7.将业务和流程进行关联，更新oa_process
        baseMapper.updateById(process);
        //记录操作审批的信息
        processRecordService.record(process.getId(),1,"发起申请");
    }

    //查询待处理列表
    @Override
    public IPage<ProcessVo> findPending(Page<ProcessVo> pageParam) {
        //1.封装查询条件，根据当前用户名查询
        TaskQuery query = taskService.createTaskQuery()
                .taskAssignee(LoginUserInfoHelper.getUsername())
                .orderByTaskCreateTime()  //降序排列
                .desc();
        //2.调用方法进行分页条件查询
        //listPage()   参数1：开始位置    参数2：每页显示记录数
        int begin=(int)((pageParam.getCurrent()-1)*pageParam.getSize());
        int size= (int) pageParam.getSize();
        List<Task> taskList = query.listPage(begin, size);
        long count = query.count();  //一共有多少条记录
        //3.将taskList封装到List<ProcessVo>。task----》process----》processVo
        List<ProcessVo> processVoList=new ArrayList<>();
        for (Task task: taskList) {
            //从task获取processId
            String processInstanceId = task.getProcessInstanceId();
            //根据processID获取实例对象
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId).singleResult();
            //从流程实例对象获取业务key,业务key也就是process的id
            String businessKey = processInstance.getBusinessKey();
            if (businessKey==null){
                continue;
            }
            //根据业务key获取process对象
            long processId = Long.parseLong(businessKey);
            Process process = baseMapper.selectById(processId);
            //将process对象复制到processvo对象
            ProcessVo processVo = new ProcessVo();
            BeanUtils.copyProperties(process,processVo);
            processVo.setTaskId(task.getId());
            //把processVo放到最终processVoList
            processVoList.add(processVo);
        }

        //4.封装返回的IPage对象
        IPage<ProcessVo> page=new Page<ProcessVo>(pageParam.getCurrent(),pageParam.getSize(),count);
        page.setRecords(processVoList);
        return page;
    }

    //获取审批详细信息
    @Override
    public Map<String, Object> show(Long id) {
        //1.根据processId获取流程信息
        Process process = baseMapper.selectById(id);
        //2.根据processId获取流程记录信息
        LambdaQueryWrapper<ProcessRecord> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(ProcessRecord::getProcessId,id);
        List<ProcessRecord> processRecordList = processRecordService.list(wrapper);
        //3.根据模板Id查询模板信息，模板id可以在process里获取
        ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());
        //4.判断当前用户是否可以进行审批：有些人可以看见这个信息，但不一定可以审批
        boolean isApprove=false;
        List<Task> taskList = this.getCurrentTaskList(process.getProcessInstanceId());
        for (Task task: taskList) {
            //判断当前审批人是否是当前用户
            if (task.getAssignee().equals(LoginUserInfoHelper.getUsername())){
                isApprove=true;
            }
        }
        //将数据封装，然后返回到map集合
        Map<String,Object> map=new HashMap<>();
        map.put("process", process);
        map.put("processRecordList", processRecordList);
        map.put("processTemplate", processTemplate);
        map.put("isApprove", isApprove);
        return map;

    }

    //进行审批
    @Override
    public void approve(ApprovalVo approvalVo) {
        //1.从approveVo获取taskId，然后获取 流程变量
        String taskId = approvalVo.getTaskId();
        Map<String, Object> variables = taskService.getVariables(taskId);
        for (Map.Entry<String,Object> entry: variables.entrySet()) {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
        //2.根据审批状态值进行判断，status=1  通过。status=-1  驳回。
        if (approvalVo.getStatus()==1){
            Map<String, Object> variable = taskService.getVariables(taskId); //流程变量，此时为空，写这个只是为了使代码更完整
            taskService.complete(taskId,variable);
        }else {
            // status===-1,结束流程
            this.endTask(taskId);
        }

        //3.记录审批过程的信息到process_record表
        String description= approvalVo.getStatus().intValue()==1?"已通过":"驳回";
        processRecordService.record(approvalVo.getProcessId(),approvalVo.getStatus(),description);
        //4.查询下一个审批人
        Process process = baseMapper.selectById(approvalVo.getProcessId());
        //查询当前任务列表
        List<Task> taskList = this.getCurrentTaskList(process.getProcessInstanceId());
        if (!CollectionUtils.isEmpty(taskList)){
            ArrayList<String> assignList = new ArrayList<>();
            for(Task task : taskList) {
                String assignee = task.getAssignee();
                SysUser sysUser = sysUserService.getUserByUsername(assignee);
                assignList.add(sysUser.getName());
                //TODO 推送消息给下一个审批人
            }
            //5.在process表更新流程信息
            process.setDescription("等待" + StringUtils.join(assignList.toArray(), ",") + "审批");
            process.setStatus(1);
        }else {
            if(approvalVo.getStatus().intValue() == 1) {
                process.setDescription("审批完成（同意）");
                process.setStatus(2);
            } else {
                process.setDescription("审批完成（拒绝）");
                process.setStatus(-1);
            }
        }
        baseMapper.updateById(process);
    }

    //查询已经处理的


    @Override
    public IPage<ProcessVo> findProcessed(Page<Process> pageParam) {
        //封装查询的条件
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery()
                .taskAssignee(LoginUserInfoHelper.getUsername())
                .finished()
                .orderByTaskCreateTime().desc();
        //调用方法进行条件分页查询
        int begin=(int)((pageParam.getCurrent()-1)*pageParam.getSize());
        int size=(int)pageParam.getSize();
        List<HistoricTaskInstance> list = query.listPage(begin, size);
        long count = query.count();  //总记录数
        //将返回的list集合封装成List<ProcessVo>
        List<ProcessVo> processVoList=new ArrayList<>();
        for (HistoricTaskInstance item:list) {
            //流程实例的Id
            String processInstanceId = item.getProcessInstanceId();
            //根据流程实例id查询到process
            LambdaQueryWrapper<Process> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Process::getProcessInstanceId,processInstanceId);
            Process process = baseMapper.selectOne(wrapper);
            ProcessVo processVo=new ProcessVo();
            if (process!=null){
                BeanUtils.copyProperties(process,processVo);
            }else {
                continue;
            }
            //放到List<ProcessVo>
            processVoList.add(processVo);
        }
        //最终使用IPage封装所有数据
        IPage<ProcessVo> pageModel=new Page<ProcessVo>(pageParam.getCurrent(),pageParam.getSize(),count);
        pageModel.setRecords(processVoList);
        return pageModel;
    }

    //查询已经发起的信息
    @Override
    public IPage<ProcessVo> findStarted(Page<ProcessVo> pageParam) {
        ProcessQueryVo processQueryVo = new ProcessQueryVo();
        processQueryVo.setUserId(LoginUserInfoHelper.getUserId());//在这里只有一个查询条件
        IPage<ProcessVo> page = baseMapper.selectPage(pageParam, processQueryVo);
        return page;
    }

    //结束流程
    private void endTask(String taskId) {
        // 1.获取当前任务对象
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //2.获取流程定义模型BpmnModel
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        List endEventList = bpmnModel.getMainProcess().findFlowElementsOfType(EndEvent.class);
        // 并行任务可能为null
        if(CollectionUtils.isEmpty(endEventList)) {
            return;
        }
        //获取节点
        FlowNode endFlowNode = (FlowNode) endEventList.get(0);  //结束节点
        FlowNode currentFlowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(task.getTaskDefinitionKey());//当前节点

        //  临时保存当前活动的原始方向
        List originalSequenceFlowList = new ArrayList<>();
        originalSequenceFlowList.addAll(currentFlowNode.getOutgoingFlows());
        //  清理当前活动方向
        currentFlowNode.getOutgoingFlows().clear();
        // 建立新流向
        SequenceFlow newSequenceFlow = new SequenceFlow();
        newSequenceFlow.setId("newSequenceFlowId");
        newSequenceFlow.setSourceFlowElement(currentFlowNode);
        newSequenceFlow.setTargetFlowElement(endFlowNode);
        List newSequenceFlowList = new ArrayList<>();
        newSequenceFlowList.add(newSequenceFlow);
        //  当前节点指向新的方向
        currentFlowNode.setOutgoingFlows(newSequenceFlowList);
        //  完成当前任务
        taskService.complete(task.getId());
    }

    //当前任务列表
    private List<Task> getCurrentTaskList(String id) {
        List<org.activiti.engine.task.Task> list = taskService.createTaskQuery().processInstanceId(id).list();
        return list;
    }
}
